package n15_设计模式_交替运行输出;

import lombok.extern.slf4j.Slf4j;

/**
 * @author fu
 * @date 2022-01-12 20:46
 * 概要：
 * ----------------------------------------------------------------
 * |                                                              |
 * |    [线程1] 输出a 5次； [线程2] 输出b 5次； [线程3] 输出c 5次； 现在要求输出 abcabcabcabcabc    |
 * |                                                            |
 * |=============================================================
 */
public class T1_alternate_by_syschronized {

    public static void main(String[] args) {

        final WaitNotify lock = new WaitNotify(1, 5);


        new Thread(()->{
            lock.print("a", 1, 2);
        }, "t1").start();
        new Thread(()->{
            lock.print("b", 2, 3);
        }, "t2").start();
        new Thread(()->{
            lock.print("c", 3, 1);
        }, "t3").start();

    }
}

/*
        输出内容    等待标记      下一个标记
        a            1              2
        b            2              3
        c            3              1
 */
@Slf4j(topic = "c.WaitNotify")
class WaitNotify {

    // 等待标记
    private int flag; // 2

    // 循环次数
    private int loopNumber;
//                         b            2              3
    public void print(String str, int waitFlag, int nextFlag){

        for (int i = 0; i < loopNumber; i++) {
            synchronized (this){

                while(flag != waitFlag){
                    try {
                        this.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                log.debug(str);
                flag = nextFlag;
                this.notifyAll();
            }
        }

    }

    public WaitNotify(int flag, int loopNumber) {
        this.flag = flag;
        this.loopNumber = loopNumber;
    }
}